package ventpipe

import (
	"encoding/json"
	"evtest/evcs"
	"evtest/setting"
	"evtest/util"
	"evtest/util/e"
)

type PipeRsp struct {
	Ret     int
	Msg     string
	OptCode int
	Data    []byte
	Err     error
}

type Pipe struct {
	EvConf *setting.EvConf
}

func (p *Pipe) PrepareData(rawData []byte) []byte {
	var evcsReqData []byte
	evcsReq := evcs.NewEvcsReq(p.EvConf.Account)
	evcsReq.EncryptData(rawData, p.EvConf.AesKey, p.EvConf.AesIv)
	evcsReq.Sign(p.EvConf.HmacKey)
	evcsReqData, _ = evcsReq.ToJson()
	return evcsReqData
}

func (p *Pipe) RequestAction(apiUrl string, evReqData []byte, token string) (pipeRsp *PipeRsp) {
	pipeRsp = &PipeRsp{}
	apiUrl = p.EvConf.Url + apiUrl
	response, err := util.HttpPost(apiUrl, evReqData, token)
	if err != nil {
		pipeRsp.OptCode = e.ERROR
		pipeRsp.Err = err
		return
	}
	evcsRsp := &evcs.EvcsRsp{}
	err = json.Unmarshal(response, evcsRsp)
	if err != nil {
		pipeRsp.OptCode = e.JSON_DECODE
		pipeRsp.Err = err
		return
	}
	pipeRsp.Ret = evcsRsp.Ret
	pipeRsp.Msg = evcsRsp.Msg
	if evcsRsp.Ret == 4002 {
		TokenPipe.Interrupt <- true
		pipeRsp.OptCode = e.TOKEN_VERIFY
		pipeRsp.Err = err
		return
	}
	if err = evcsRsp.VerifyNoticeResult(p.EvConf.HmacKey); err != nil {
		pipeRsp.OptCode = e.SIGN_VERIFY
		pipeRsp.Err = err
		return
	}
	jsonBytes, err := evcsRsp.Decrypt(p.EvConf.AesKey, p.EvConf.AesIv)
	if err != nil {
		pipeRsp.OptCode = e.DATA_DECRYPT
		pipeRsp.Err = err
		return
	}
	pipeRsp.Data = jsonBytes
	return
}
